package com.example.music.adapter;

import static android.content.ContentValues.TAG;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.music.R;
import com.example.music.activity.PlaylistDetailActivity;
import com.example.music.db.PlaylistDAO;
import com.example.music.model.Song;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PlaySongListAdapter extends RecyclerView.Adapter<PlaySongListAdapter.ViewHolder> {
    private List<PlaylistDAO.Playlist> playlists;
    private PlaylistDAO playlistDao;
    private Context context;

    public PlaySongListAdapter(Context context, List<PlaylistDAO.Playlist> playlists, PlaylistDAO playlistDao) {
        this.context = context;
        this.playlists = playlists;
        this.playlistDao = playlistDao;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_playlist, parent, false);
        return new ViewHolder(view);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        PlaylistDAO.Playlist playlist = playlists.get(position);
        holder.name.setText(playlist.getName());

        // 初始化或清空歌曲列表
        List<Song> songList = new ArrayList<>();

        // 获取歌单中的歌曲路径
        List<String> songPaths = playlistDao.getSongsInPlaylist(playlist.getId());

        Log.d(TAG, "Loaded song paths: " + songPaths);

        // 从媒体库加载歌曲信息
        try (Cursor cursor = context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{
                        MediaStore.Audio.Media.TITLE,
                        MediaStore.Audio.Media.ARTIST,
                        MediaStore.Audio.Media.ALBUM,
                        MediaStore.Audio.Media.DATA,
                        MediaStore.Audio.Media.DURATION
                },
                MediaStore.Audio.Media.DATA + " IN (" + makePlaceholders(songPaths.size()) + ")",
                songPaths.toArray(new String[0]),
                null
        )) {
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                    String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                    String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
                    String filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                    long duration = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));

                    Song song = new Song(title, artist, album, filePath);
                    song.setDuration(duration);
                    // 获取专辑封面
                    Bitmap albumCover = getAlbumArt(filePath);
                    song.setAlbumCover(albumCover);
                    songList.add(song);
                    Log.d(TAG, "Added song: " + song.getTitle());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        holder.textSongCount.setText(songList.size() + "首");
        if (!songList.isEmpty() && songList.get(0).getAlbumCover() != null) {
            holder.playlistCover.setImageBitmap(songList.get(0).getAlbumCover());
        } else {
            holder.playlistCover.setImageResource(R.drawable.ic_menu);
        }
        holder.itemView.setOnClickListener(v -> {
            Intent intent = new Intent(context, PlaylistDetailActivity.class);
            intent.putExtra("playlist_id", playlist.getId());
            intent.putExtra("playlist_name", playlist.getName());
            context.startActivity(intent);
        });

        holder.delete.setOnClickListener(v -> {
            int pos = holder.getAdapterPosition();
            if (pos != RecyclerView.NO_POSITION) {
                playlistDao.deletePlaylist(playlist.getId());
                playlists.remove(pos);
                notifyItemRemoved(pos);
            }
        });
    }

    @Override
    public int getItemCount() {
        return playlists.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView name;
        ImageView delete;
        private ImageView playlistCover;
        private TextView textSongCount;

        ViewHolder(View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.text_playlist_name);
            delete = itemView.findViewById(R.id.img_delete);
            playlistCover = itemView.findViewById(R.id.img_cover);
            textSongCount = itemView.findViewById(R.id.text_song_count);
        }
    }

    private Bitmap getAlbumArt(String filePath) throws IOException {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            byte[] artBytes = retriever.getEmbeddedPicture();
            if (artBytes != null) {
                return BitmapFactory.decodeByteArray(artBytes, 0, artBytes.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return null;
    }

    private String makePlaceholders(int length) {
        if (length <= 0) {
            return ""; // 如果长度小于等于0，返回空字符串
        }
        StringBuilder sb = new StringBuilder(length * 2);
        for (int i = 0; i < length; i++) {
            if (i > 0) {
                sb.append(", ");
            }
            sb.append("?");
        }
        return sb.toString();
    }

    // 添加 updateData 方法
    public void updateData(List<PlaylistDAO.Playlist> newPlaylists) {
        // 使用 DiffUtil 进行高效更新（可选）
        this.playlists.clear();
        this.playlists.addAll(newPlaylists);
        notifyDataSetChanged();

        // 或者更高效的更新方式：
    /*
    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new PlaylistDiffCallback(this.playlists, newPlaylists));
    this.playlists.clear();
    this.playlists.addAll(newPlaylists);
    diffResult.dispatchUpdatesTo(this);
    */
    }
}



